<script setup>
import { getUserOrder,getCheckListAPI,getFinishOrder,getUnpaidOrder,sendComment,deleteOrder } from '@/apis/order'
import { ElMessage } from 'element-plus'
import { createOrderAPI } from "@/apis/checkout";
import { getPayAPI,getTopUpAPI,getBalanceAPI } from "@/apis/pay.js";
import {  ref } from 'vue'
import {useRouter} from 'vue-router'
const router=useRouter()
const dialogInfo=ref(false)
// tab列表
const tabTypes = [
  { name: "all", label: "全部订单" },
  { name: "unpay", label: "已付款" },
  // { name: "deliver", label: "待发货" },
  // { name: "receive", label: "待收货" },
  // { name: "comment", label: "待评价" },
  { name: "complete", label: "待支付" },
  // { name: "cancel", label: "已取消" }
]
// 获取订单列表
const orderList = ref([])
const total = ref(0)
const params = ref({
  orderState: 0,
  page: 1,
  pageSize: 2
})
// const productList=ref([])
const getOrderList = async () => {
  const res = await getUserOrder()
  console.log('订单全部列表',res.data.data);
  //倒序数组
  res.data.data.reverse()
  orderList.value = res.data.data
  // setTimeout(()=>{
  //   productList.value=res.data.data.products
  // },1000)
  
  // console.log("订单商品为",productList.value);
  // console.log("订单列表为",orderList.value.products);
  // total.value = res.result.counts
}

getOrderList()

const pageTotal=ref(orderList.value.length)

// tab切换
const tabChange = (type) => {
  pageTotal.value=0
  console.log(type)
  orderList.value=[]
  const getOrderList = async () => {
  console.log("dasdasd")
  if(type==0)
  {
    const res = await getUserOrder()
    console.log("ads",res.data.data);
    res.data.data.reverse()
    orderList.value = res.data.data
    pageTotal.value=orderList.value.length
  }else if(type==2){
    const res = await getUnpaidOrder()
    console.log(res.data.data);
    res.data.data.reverse()
    orderList.value = res.data.data
    pageTotal.value=orderList.value.length
  }else{
    const res = await getFinishOrder()
    console.log(res.data.data);
    res.data.data.reverse()
    orderList.value = res.data.data
    pageTotal.value=orderList.value.length
  }
  // total.value = res.result.counts
}
  // params.value.orderState = type
  getOrderList()
}

// 页数切换
// const pageChange = (page) => {
//   console.log(page)
//   params.value.page = page
//   getOrderList()
// }
//888888888888888888888888888888888888888888888888
const payForm=ref({
  password:'',
  payMoney:''
})
const payShow=ref(false)
const orderId=ref()
const SumPrice=ref()
const submitOrder=(id,price)=>{
  console.log('价格',price);
  payForm.value.payMoney=price
  SumPrice.value=price
  payShow.value=true
  orderId.value=id
  // console.log('订单',id);
  // const getCheckListRes=await getCheckListAPI(id)
  // getCheckListRes.data.data.payStatus=1
  // const res1=await createOrderAPI(getCheckListRes.data.data)
  // console.log('创建订单',res1.data);
}
const Balance=ref(0)
const getBalance=async()=>{
    const res=await getBalanceAPI()
  
    Balance.value=res.data.data
    console.log('余额',Balance.value)
  }
  getBalance()
const submitPay=async()=>{
  // payShow.value=true
  if(Balance.value<payForm.value.payMoney)
  {
    ElMessage.error("余额不足,请充值")
    //11
    
    router.push('/member/balance')
  }else{
    const getCheckListRes=await getCheckListAPI(orderId.value)
    getCheckListRes.data.data.payStatus=1
    const res1=await createOrderAPI(getCheckListRes.data.data)
    console.log('创建订单',res1.data);
    console.log('支付信息',payForm.value);
    const res=await getPayAPI(payForm.value)
    console.log(res);
    payShow.value = false
    await deleteOrder(orderId.value)
    ElMessage.success("支付成功")
  }
  // console.log('支付信息');
}

const fomartPayState = (payState) => {
  const stateMap = {
    0: '待付款',
    // 2: '待发货',
    // 3: '待收货',
    // 4: '待评价',
    1: '已完成',
    // 6: '已取消'
  }
  return stateMap[payState]
}
const productInfo=ref([])
const showInfo=async(id)=>{
  const res=await getCheckListAPI(id)
  dialogInfo.value=true

  productInfo.value=res.data.data
  console.log("订单详情",res.data.data);
}
const lookComment=ref(false)
const commentText=ref('')
const productId=ref()
const showComment=(id)=>{
  // console.log(id);
  productId.value=id
  // console.log("评论",commentText.value);
  lookComment.value=true
}

const submitComment=async()=>{
  let obj={
  content: "",
  date: "",
  id: 0,
  orient: 0,
  orientId: 0,
  pictures: [],
  userId: 0
  }
  obj.content=commentText.value
  const res=await sendComment(productId.value,obj)
  setTimeout(()=>{
    console.log("评论",res);
  })
  ElMessage.success('评论成功')
  lookComment.value=false
}

</script>

<template>
  <div class="order-container">
    <el-tabs @tab-change="tabChange">
      <!-- tab切换 -->
      <el-tab-pane v-for="item in tabTypes" :key="item.name" :label="item.label" />

      <div class="main-container">
        <div class="holder-container" v-if="orderList.length === 0">
          <el-empty description="暂无订单数据" />
        </div>
        <div v-else>
          <!-- 订单列表 -->
          <div class="order-item" v-for="order in orderList" :key="order.id">
            <div class="head">
              <span>下单时间：{{ order.time }}</span>
              <span>订单编号：{{ order.id }}</span>
              <!-- <span>收货人：{{ order.receiverContact }}</span>
              <span>手机号：{{ order.receiverMobile }}</span>
              <span>收货地址：{{ order.receiverAddress }}</span> -->
              <span class="del" v-if="order.orderState === 6">已取消</span>
              <span class="del" v-else-if="order.orderState === 5">已完成</span>
              <!-- 未付款，倒计时时间还有 -->
              <!-- <span class="down-time" v-if="order.orderState === 1">
                <i class="iconfont icon-down-time"></i>
                <b>付款截止: {{ order.countdown }}</b>
              </span> -->
            </div>
            <div class="body">
              <div class="column goods">
                <ul>
                  <li v-for="(item) in order.products" :key="item.id">
                    <a class="image" href="javascript:;">
                      <img :src="item.mainPicture" alt="" />
                    </a>
                    <div class="info">
                      <p class="name ellipsis-2">
                        {{ item.name }}
                      </p>
                      <p class="attr ellipsis">
                        <span>{{ item.description }}</span>
                      </p>
                    </div>
                    <div class="price">¥{{ item.price?.toFixed(2) }}</div>
                  </li>
                </ul>
              </div>
              <div class="column state">
                <p>{{ fomartPayState(order.orderState) }}</p>
                <p v-if="order.orderState === 3">
                  <a href="javascript:;" class="green">查看物流</a>
                </p>
                <p v-if="order.orderState === 4">
                  <a href="javascript:;" class="green">评价商品</a>
                </p>
                <p v-if="order.orderState === 5">
                  <a href="javascript:;" class="green">查看评价</a>
                </p>
              </div>
              <div class="column amount">
                <p class="red">¥{{ (order.totalPrice+8).toFixed(2) }}</p>
                <p>（含运费：¥8.00）</p>
                <p>茶币支付</p>
                <el-button link style="color: #1dc779;margin-top: 5px;font-size: 18px;" v-if="!order.payStatus" @click="submitOrder(order.id,(order.totalPrice+8))">点击支付</el-button>
                <p style="color: gold;" v-else>正在配送…</p>
              </div>
              <div class="column action">
                <el-button v-if="order.orderState === 1" type="primary" size="small">
                  立即付款
                </el-button>
                <el-button v-if="order.orderState === 3" type="primary" size="small">
                  确认收货
                </el-button>
                <p><el-button @click="showInfo(order.id)" >查看详情</el-button></p>
                <p v-if="[2, 3, 4, 5].includes(order.orderState)">
                  <a href="javascript:;">再次购买</a>
                </p>
                <p v-if="[4, 5].includes(order.orderState)">
                  <a href="javascript:;">申请售后</a>
                </p>
                <p v-if="order.orderState === 1"><a href="javascript:;">取消订单</a></p>
              </div>
            </div>
          </div>
          <!-- 分页 -->
          
        </div>
      </div>

    </el-tabs>
  </div>

  <el-dialog v-model="dialogInfo"  width="800">
  <h1 style="text-align: center;margin-bottom: 30px;">订单详情</h1>
  <h2>个人信息：</h2>
  <div class="imageInfo">
    <p>收货人：{{ productInfo.address.userName}}</p>
    <p>电话号码：{{ productInfo.address.phoneNumber }}</p>
    <p>收货地址：{{ productInfo.address.address }}</p>
  </div>
  <!-- <p>{{  }}</p> -->
  <h2>商品：</h2>
    <div class="body">
      <div class="order-container">
        <div class="main-container">
          <div>
            <div class="order-item">
              <div class="body">
                <div class="column goods">
                 <div>
                  <ul>
                    <li v-for="(item) in productInfo.products" :key="item.id">
                      <a class="image" href="javascript:;">
                        <img :src="item.mainPicture" alt="" />
                      </a>
                       <div class="info">
                        <p class="name ellipsis-2">
                           {{ item.name }}
                        </p>
                        <p class="attr ellipsis">
                        <span>{{ item.description }}</span>
                        </p>
                        </div>
                          <div class="price">¥{{ item.price?.toFixed(2) }}</div>
                        <div class="count">x{{ item.count }} </div>
                        <el-button size="large" style="margin-left: 150px" @click="showComment(item.id)">去评价</el-button>
                    </li>
                  </ul>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <h2>总额：¥{{ productInfo.totalPrice }}</h2>
    
  </el-dialog>

<el-dialog v-model="lookComment">
  <h1 style="text-align: center;margin-bottom: 30px;">评价</h1>
    <p>评价内容：</p>
    <el-input
      type="textarea"
      :rows="2"
      placeholder="请输入内容"
      v-model="commentText"
    ></el-input>
    <el-button type="primary" @click="submitComment" style="margin-left: 700px;margin-top: 30px;">提交评价</el-button>
</el-dialog>

<div>
<el-dialog title="茶币支付" v-model="payShow" style="width: 500px;">
    <el-form :model="payForm" label-width="100px">
      <el-form-item label="支付金额：">
        ¥{{ SumPrice.toFixed(2) }}
      </el-form-item>
      <el-form-item label="支付密码：">
        <el-input v-model="payForm.password" type="password" placeholder="支付密码与登录密码一致"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="payShow = false">取消</el-button>
      <el-button type="primary" @click="submitPay">确认支付</el-button>
    </template>
  </el-dialog>
</div>
</template>

<style scoped lang="scss">

.imageInfo{
  //居中
  font-size: 20px;
  line-height: 40px;
  // text-align: center;
  margin-left:100px
}


.order-container {
  padding: 10px 20px;

  .pagination-container {
    display: flex;
    justify-content: center;
  }

  .main-container {
    min-height: 500px;

    .holder-container {
      min-height: 500px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.order-item {
  margin-bottom: 20px;
  border: 1px solid #f5f5f5;

  .head {
    height: 50px;
    line-height: 50px;
    background: #f5f5f5;
    padding: 0 20px;
    overflow: hidden;

    span {
      margin-right: 20px;

      &.down-time {
        margin-right: 0;
        float: right;

        i {
          vertical-align: middle;
          margin-right: 3px;
        }

        b {
          vertical-align: middle;
          font-weight: normal;
        }
      }
    }

    .del {
      margin-right: 0;
      float: right;
      color: #999;
    }
  }

  .body {
    display: flex;
    align-items: stretch;

    .column {
      border-left: 1px solid #f5f5f5;
      text-align: center;
      padding: 20px;

      >p {
        padding-top: 10px;
      }

      &:first-child {
        border-left: none;
      }

      &.goods {
        flex: 1;
        padding: 0;
        align-self: center;

        ul {
          li {
            border-bottom: 1px solid #f5f5f5;
            padding: 10px;
            display: flex;

            &:last-child {
              border-bottom: none;
            }

            .image {
              width: 70px;
              height: 70px;
              border: 1px solid #f5f5f5;
            }

            .info {
              width: 220px;
              text-align: left;
              padding: 0 10px;

              p {
                margin-bottom: 5px;

                &.name {
                  height: 38px;
                }

                &.attr {
                  color: #999;
                  font-size: 12px;

                  span {
                    margin-right: 5px;
                  }
                }
              }
            }

            .price {
              width: 100px;
            }

            .count {
              width: 80px;
            }
          }
        }
      }

      &.state {
        width: 120px;

        .green {
          color: $xtxColor;
        }
      }

      &.amount {
        width: 200px;

        .red {
          color: $priceColor;
        }
      }

      &.action {
        width: 140px;

        a {
          display: block;

          &:hover {
            color: $xtxColor;
          }
        }
      }
    }
  }
}
</style>